import { Injectable, Inject } from '@nestjs/common';
import { CreateArticleDto, getArticleListDto, getArticleDetailDto } from './dto/create-article.dto';
import { UpdateArticleDto } from './dto/update-article.dto';
import { Like, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Article } from './entities/article.entity';
import { User } from '../user/entities/user.entity';
import { LoginService } from '../login/login.service';
import { Comment } from '../comment/entities/comment.entity';
import { CollectService } from '../collect/collect.service';
import { BusinessException } from '../../common/exceptions/business.exception';
@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(User) private readonly user: Repository<User>,
    @InjectRepository(Article) private readonly article: Repository<Article>,
    @InjectRepository(Comment) private readonly comment: Repository<Comment>,
    private readonly CollectService: CollectService,
  private readonly loginService: LoginService) { }
  async create(createArticleDto: CreateArticleDto) {
    // 假设 createArticleDto 里有 userId
    const user = await this.user.findOne({ where: { userid: createArticleDto.userid } });
    if (!user) throw new Error('用户不存在');

    const article = this.article.create({
      ...createArticleDto,
      user, // 这里自动建立关联
    });
    return this.article.save(article);
  }

  async findAll(query: getArticleListDto, req?: any) {
    
    const data = await this.article.find({
      relations: ['user'],
      where: {
        title: Like(`%${query.keyword}%`)
      },
      order: {
        [`${query.sort}`]: 'DESC'
      },
      skip: (query.page - 1) * query.pageSize,
      take: query.pageSize
    })
    
    //将时间戳转换成字符串并去掉秒的小数
    const newData: any = [];
    for (let index = 0; index < data.length; index++) {
      const item = { ...data[index], create_time: '' };
      item.create_time = data[index].create_time.toString().slice(0, 19);
      newData.push(item)
    }

    return newData;
  }
  async findAllbyuser(userid, req?: any) {

    const userLoginState = this.loginService.getLoginUser(req);
    const data = await this.article.find({
      where: { user: { userid: userid.userid } },
      relations: ['user', 'comments'],
    });
    return data
  }
  async findOne(articleid) {

    const collectService = await this.CollectService.findAllbyarticleid(articleid.articleid);

    const data: any = await this.article.findOne({
      where: { articleid: articleid.articleid },
      relations: ['user']
    });
    data.iscollect = 0;
    console.log('articleid', articleid);

    for (let index = 0; index < collectService.length; index++) {
      const element = collectService[index];
      if (element.userid == articleid.userid) {
        data.iscollect = 1;
      }
    }
    data.collects = collectService.length;
    return data
  }

  update(id: number, updateArticleDto: UpdateArticleDto) {
    return `This action updates a #${id} article`;
  }

  remove(id: number) {
    return `This action removes a #${id} article`;
  }
  //点赞
  async like(articleid) {
    const article = await this.article.findOne({ where: { articleid: articleid.articleid } });
    if (!article) throw new Error('文章不存在');
    article.like += 1;
    return this.article.save(article);
  }
}
